package com.lyw.utils;

import com.lyw.game.Address;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseAddressUtil {

  private BaseAddressUtil() {}

  public static void convertBaseAddress(String baseAddressPath) {

    try {
      List<String> allLines = Files.readAllLines(Paths.get(baseAddressPath), StandardCharsets.UTF_8);
      List<String> templateAllLines = Files.readAllLines(Paths.get("C:\\Users\\Administrator\\Desktop\\TPlan\\TPlan\\src\\main\\resources\\address_template.txt"), StandardCharsets.UTF_8);
      Map<String, String> addressMap = new HashMap<>();
      for (String line : allLines) {
        if (line.contains(".常量")) {
          String[] s = line.split(" ");
          String addressName = s[1].split(",")[0];
          addressMap.put(addressName, s[3]);
        }
      }
      File temp = new File("temp.txt");
      FileWriter writer = new FileWriter(temp, StandardCharsets.UTF_8);
      for (String templateLine : templateAllLines) {
        if (templateLine.contains("//")) {
          String[] s = templateLine.strip().split(" ");
          String addressName = s[s.length - 1];
          String address = addressMap.get(addressName);
          templateLine = templateLine.substring(0, templateLine.lastIndexOf("=") + 2) + (address != null ? address + "L" : 0) + "; // " + addressName;
        }
        writer.write(templateLine + "\n");
      }
      writer.flush();
      writer.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
